package com.fh.alipay.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fh.alipay.annotation.Authorize;
import com.fh.alipay.utils.MD5Utils;
import com.fh.alipay.vo.ApiResult;

import javax.annotation.Resource;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.fh.alipay.po.User;
import com.fh.alipay.service.IUserService;
import com.fh.alipay.model.dto.UserDTO;
import com.fh.alipay.model.vo.UserVO;
import com.fh.alipay.model.query.UserQuery;
import com.fh.alipay.model.convert.UserConvert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.web.bind.annotation.RestController;

/**
 * @author fh
 * @date 2022-05-03
 * @description 管理用户控制器
 */
@RestController
@RequestMapping("/aliPay/user")
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserController extends BaseController {

    @Resource
    private IUserService userService;

    private static final AtomicInteger atomicInteger = new AtomicInteger(3);

    /**
     * 登录
     *
     * @param
     * @param bindingResult
     * @return
     */
    @PostMapping("/login")
    public ApiResult login(@Valid UserDTO dto, BindingResult bindingResult) {
        log.info("login User:{}", dto);
        if (bindingResult.hasErrors()) {
            return ApiResult.error("参数填写错误：" + Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }

        User user = userService.getOne(Wrappers.lambdaQuery(User.class)
                .select(User::getUsername, User::getPassword, User::getUserType)
                .eq(User::getUsername, dto.getUsername())
                .eq(User::getPassword, MD5Utils.MD5(dto.getPassword())));
        if (null != user) {
            String token = getToken(user);
            Map<String, Object> map = new HashMap<>();
            map.put("userType", user.getUserType());
            map.put("token", token);
            return ApiResult.ok(map);
        }
        return ApiResult.error("login fail:用户不存在");
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
//    @Authorize
    public ApiResult<String> add(UserDTO dto) {
        User po = UserConvert.toPO(dto);
        String password = po.getPassword();
        if (StrUtil.isNotBlank(password)) {
            password = MD5Utils.MD5(password);
        }
        po.setPassword(password);
        po.setUserType(atomicInteger.getAndIncrement());
        boolean save = userService.save(po);
        return save ? ApiResult.ok() : ApiResult.fail();
    }

    /**
     * 编辑用户
     */
    @PostMapping("/update")
//    @Authorize
    public ApiResult update(@Valid UserDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ApiResult.error("参数填写有误");
        }
        User user = userService.getById(dto.getId());
        if (null != user) {
            if (user.getPassword().equals(MD5Utils.MD5(dto.getLastPassword()))) {
                String dtoPassword = dto.getPassword();
                String confirmPassword = dto.getConfirmPassword();
                if (dtoPassword.equals(confirmPassword)) {
                    User po = UserConvert.toPO(dto);
                    String password = po.getPassword();
                    po.setPassword(MD5Utils.MD5(password));
                    boolean update = userService.updateById(po);
                    return update ? ApiResult.ok(po) : ApiResult.fail();
                }
                return ApiResult.error("请保持新密码输入一致");
            }
            return ApiResult.error("旧密码输入有误");
        }
        return ApiResult.error("用户不存在");
    }

//    public static void main(String[] args) {
//        System.out.println(MD5Utils.MD5("admin"));
//    }
}
